package com.maxd.modules.selfshop.merchants.service;

import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.SelfOrderRemind;
import com.maxd.modules.selfshop.merchants.entity.SelfStoreComplain;
import com.maxd.modules.selfshop.merchants.respository.SelfStoreComplainJpaRepository;
import com.maxd.modules.selfshop.merchants.respository.SelfStoreJpaRepository;
import com.maxd.respository.admin.AdminJpaRepository;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.selfOrderRemind.SelfOrdersRemindJpaRepository;
import com.maxd.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class SelfStoreComplainServiceImpl implements SelfStoreComplainService{
    @Autowired
    private SelfStoreComplainJpaRepository jpaRepository;
    @Autowired
    private SelfOrdersRemindJpaRepository selfOrdersRemindJpaRepository;
    @Autowired
    private AdminJpaRepository adminJpaRepository;
    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private SelfStoreJpaRepository selfStoreJpaRepository;

    @Override
    public Result findAll(Integer page, Integer size, String storeName, Integer status) {
        //按照时间排序
        Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime")));
        //构造自定义查询条件
        Specification<SelfStoreComplain> queryCondition = new Specification<SelfStoreComplain>() {
            @Override
            public Predicate toPredicate(Root<SelfStoreComplain> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotEmpty(storeName)) {
                    predicateList.add(criteriaBuilder.like(root.get("storeName"), "%"+storeName+"%"));
                }
                if (status != 0) {
                    predicateList.add(criteriaBuilder.equal(root.get("status"), status));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(jpaRepository.findAll(queryCondition, pageable));
    }

    @Override
    public Result storeList(Integer page, Integer size, Integer status, Long merchantId) {
        //按照时间排序
        Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime")));
        //构造自定义查询条件
        Specification<SelfStoreComplain> queryCondition = new Specification<SelfStoreComplain>() {
            @Override
            public Predicate toPredicate(Root<SelfStoreComplain> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (status != 0) { //状态（1待处理 2投诉驳回 3商家处理 4商家已处理 5总后台已处理）
                    predicateList.add(criteriaBuilder.equal(root.get("status"), status)); //需要商家处理的
                }
                predicateList.add(criteriaBuilder.equal(root.get("merchantId"), merchantId));
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(jpaRepository.findAll(queryCondition, pageable));
    }

    @Override
    public Result userList(Integer page, Integer size, Long userId) {
        //按照时间排序
        Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime")));
        //构造自定义查询条件
        Specification<SelfStoreComplain> queryCondition = new Specification<SelfStoreComplain>() {
            @Override
            public Predicate toPredicate(Root<SelfStoreComplain> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.equal(root.get("userId"), userId));
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(jpaRepository.findAll(queryCondition, pageable));
    }

    @Override
    public Result saveBody(SelfStoreComplain entity) {
        entity.setCreateTime(DateUtil.createTime());
        entity.setStatus(1); //待处理
        SelfStoreComplain save = jpaRepository.save(entity);
        // 给总后台发送消息
        SelfOrderRemind r = new SelfOrderRemind();
        r.setCreateTime(DateUtil.createTime());
        r.setStatus(1); //未读
        r.setType(2); //投诉消息
        selfOrdersRemindJpaRepository.save(r);
        return ResultUtil.success(save);
    }

    @Override
    public Result updateBody(SelfStoreComplain entity) {
        return ResultUtil.success(jpaRepository.save(entity));
    }

    @Override
    public Result findOne(Long id) {
        return ResultUtil.success(jpaRepository.findById(id).orElse(null));
    }


    @Override
    public Result delete(Long id) {
        jpaRepository.deleteById(id);
        return ResultUtil.success();
    }

    /**
     * 处理投诉
     * @param id
     * @param status 1待处理 2投诉驳回 3商家处理中 4商家已处理 5总后台已处理
     * @param refundReason
     * @return
     */
    @Override
    public Result deal(Long id, Integer status, String refundReason) {
        SelfStoreComplain s = jpaRepository.findById(id).orElse(null);
        s.setStatus(status);
        if (status == 2){
            s.setRefundReason(refundReason);
        }else if(status == 3){ //投诉属实
            // 1.给商家发送消息
            SelfOrderRemind r = new SelfOrderRemind();
            r.setMerchantId(s.getMerchantId()); //商户id
            r.setCreateTime(DateUtil.createTime());
            r.setStatus(1); //未读
            r.setType(2); //投诉待处理
            selfOrdersRemindJpaRepository.save(r);
            //店铺评分减少
            Integer score = Integer.valueOf(commonRepository.findOne(100).getValue());
            selfStoreJpaRepository.lessScore(score, s.getStoreId());
        }else if(status == 5){ //投诉总后台确认处理完毕
            // 1.给总后台发送消息
            SelfOrderRemind r = new SelfOrderRemind();
            r.setCreateTime(DateUtil.createTime());
            r.setStatus(1); //未读
            r.setType(2); //投诉待处理
            selfOrdersRemindJpaRepository.save(r);
        }
        SelfStoreComplain save = jpaRepository.save(s);
        return ResultUtil.success(save);
    }
}
